package org.wavetech.scrollingcascade;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class HeaderSnap extends RecyclerView.OnScrollListener {

    private final int range;
    private final int limit;

    private HeaderSnap(int range, int limit) {
        this.range = range;
        this.limit = limit;
    }

    public static void attach(RecyclerView recyclerView, int range,int limit) {
        recyclerView.addOnScrollListener(new HeaderSnap(range, limit));
    }

    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        if (newState != RecyclerView.SCROLL_STATE_IDLE) return;
        int offset = recyclerView.computeVerticalScrollOffset();
        if (offset < limit) {
            recyclerView.smoothScrollBy(0, -offset);
        } else if (offset > limit && offset < range) {
            recyclerView.smoothScrollBy(0, range - offset);
        }
    }
}
